package cn.micai.base.thread;

import java.math.BigInteger;
import java.util.concurrent.BlockingQueue;

/**
 * 使用interrupt()实现可取消的任务
 *
 * Created by zhaoxinguo on 2017/8/23.
 */
public class PrimeProducer extends Thread {

    private final BlockingQueue<BigInteger> queue;

    public PrimeProducer(BlockingQueue<BigInteger> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        try {
            BigInteger p = BigInteger.ONE;
            //轮询中断标志位，判断是否需要取消任务
            while (!Thread.currentThread().isInterrupted()){
                queue.put(p = p.nextProbablePrime());
            }
        }catch (InterruptedException consumed){
            /* 任务被取消，退出。这里对中断的处理方式就是退出任务，因此可以swallow */
            consumed.printStackTrace();
        }
    }

    //发起中断，取消任务执行
    public void cancel(){
        interrupt();
    }

}
